//
//  CTVMediaDownloadController.m
//  Channltv
//
//  Created by Bruno Keymolen on 29/08/07.
//  Copyright 2007 channl.tv. All rights reserved.
//

#import "CTVMediaDownloadController.h"
#import "CTVUtil.h"
#import "CTVCache.h"
#import "CTVChannelPlayerController.h"
#import "CTVConfig.h"

@implementation CTVMediaDownloadController

- (id)initWithScene: (BRRenderScene *) scene  andClip:(CTVClip*)clip andImage:(CGImageRef)img andMediaDownload:(CTVHTTPMediaDownload*)mediaDownload andTitle:(NSString*)title forChannel:(CTVChannel*)channel{
//- (id)initWithScene: (BRRenderScene *) scene andClip:(CTVClip*)clip andImage:(CGImageRef)img andMediaDownload:(CTVHTTPMediaDownload*)mediaDownload andTitle:(NSString*)title{

    self = [super initWithScene: scene]; 
	if(self == nil ){
        return ( nil );
	}

	m_playClipNow = FALSE;
	m_skipClip = FALSE;

	m_clip = clip;
	[m_clip retain];
	
	m_channel = channel;
	[m_channel retain];
	
	[title retain];
	m_title = title;
	m_downloader = mediaDownload;
	
	m_filesize = [m_downloader downloadFileLength];
	m_urlString = [m_downloader urlString]; 
	[m_urlString retain];

	//Lay-Out	
	NSRect masterFrame = [[self masterLayer] frame];
	
	
	//Create the layers and controlls
	
	
	/*
	 * Image
	 */	
	_image = [[BRImageControl alloc] initWithScene: [self scene]];
    [_image setReflectionAmount: 0.00f];
    [_image setReflectionOffset: 0.02f];
    [_image setImage: img];	
    NSRect frame = masterFrame;    	
	frame.size = [_image pixelBounds];
	//Resize frame to 45% of the height (keep aspect ratio)
	float oriHeight = frame.size.height;
	float availableHeight = masterFrame.size.height;
	frame.size.height = availableHeight * 0.55f;
	//Aspect ratio
	float pc = frame.size.height/oriHeight;	
	frame.size.width = frame.size.width * pc;			
	//Center at top of the screen (95%)
    frame.origin.y = ((masterFrame.origin.y + masterFrame.size.height) - frame.size.height) * 0.90f;
    frame.origin.x = masterFrame.origin.x + (((masterFrame.size.width) - frame.size.width) * 0.5f);
    [_image setFrame: frame];
    // add it to our master layer
    [self addControl: _image];


	
	/* Progress Bar */
	m_progressBarContoller = [[CTVDownloadController alloc] initWithScene:scene];
	NSRect barframe = [_image frame];    
	barframe.size.height = (masterFrame.size.height) * 0.20f; 
	barframe.size.width = (masterFrame.size.width) * 0.7f; 
	barframe.origin.x = (masterFrame.size.width - barframe.size.width) * 0.5f;
	barframe.origin.y = barframe.origin.y - barframe.size.height;
	if(m_title != nil){
		[m_progressBarContoller setText:m_title]; 
	}
	if(m_filesize > 0){
		NSString* tmpstr = [NSString stringWithFormat:@"%d MB", (m_filesize/(1024*1024))];  
		[m_progressBarContoller setMB:tmpstr]; 
	}
	if([m_downloader downloadFileLength] > 0 && [m_downloader downloadedLength] > 0){
		float prog = ((float)[m_downloader downloadedLength] / (float)[m_downloader downloadFileLength]) * 100.0f;
		[m_progressBarContoller setPercent:(int)prog]; 	
	}
	[m_progressBarContoller setFrame: barframe];
	[self addControl: m_progressBarContoller];
	

	NSSize size = ([[self masterLayer] frame]).size;

//	//Ok and Abort are buttons but we have to use a Menu for it because buttons are alway's selected
//	//Ok button
//	m_okButton = [[BRButtonControl alloc] initWithScene:[self scene] masterLayerSize:size];
//	[m_okButton setTitle:@"Menu"];
//	[m_okButton setTarget:self];
//	[m_okButton setAction:@selector(finishClipDownload)];
//	[m_okButton setYPosition:20];
//	//[self addControl: m_okButton];	
	
	
	//Abort button
	m_abortButton = [[BRButtonControl alloc] initWithScene:[self scene] masterLayerSize:size];
	[m_abortButton setTitle:@"Abort Download"];
	[m_abortButton setTarget:self];
	[m_abortButton setAction:@selector(abortClipDownload)];
	[m_abortButton setYPosition: 20];//[m_okButton frame].size.height ];
	[self addControl: m_abortButton];
	

///TEST///	
//{
//
//CTVOptionDialog* options = [[CTVOptionDialog alloc] initWithScene:[self scene]];
//[options addOptionText:@"Bruno"];
//[options addOptionText:@"Ruth" isDefault:YES];
//[options setActionSelector:@selector(menuClipDownload) target:self];
//[options setFrame:frame];
//[self addControl: options];
//[[self stack] pushController: options];
//}	
	
	
	
	//Subscribe for events
	[m_downloader addDownloadUpdate:(CTVMediaDownloadUpdate*)self];

    return ( self );
}


-(void)abortClipDownload{
	NSLog(@"ABORT PRESSED");
	if(m_downloader){
		[m_downloader removeDownloadUpdate:(CTVMediaDownloadUpdate*)self];
		[m_downloader stopDownload];
		m_downloader = nil;
	}
	[m_abortButton setAction:@selector(finishClipDownload)];
	[m_abortButton  setTitle:@"Download Stopped by User"];
	[[self scene] renderScene];
}
	

-(void)finishClipDownload{
	//Remove from screen
	[[self stack] removeController:self];
}

-(void)playClipDownload{
	m_playClipNow = TRUE;
//	id controller = [[[CTVChannelPlayerController alloc] initWithScene:[self scene] forChannel:m_channel startWithClip:m_clip] autorelease];
//	[[self stack] pushController:controller];
//	[controller playClip];

	//We are not needed any more, remove ourselve from screen
	[[self stack] removeController:self];
}


- (void) dealloc
{
	if(m_timer != nil){
		[m_timer retain];
	}
    [_image release];
	[m_progressBarContoller release];
	[m_abortButton release];
//	[m_okButton release];
	[m_title release];
	[m_urlString release];
	[m_clip release];
	[m_channel release];
	
	if(m_downloader){
		//Unsubscribe (if still exist)
		[m_downloader removeDownloadUpdate:(CTVMediaDownloadUpdate*)self];
	}

    [super dealloc];
}


- (id)layer{
	return _master;
}

- (void)activate{
	
}

- (void)willLoseFocus{

}

- (void)willRegainFocus{

}

- (void)willDeactivate{

}

- (void)deactivate{

}

- (BOOL)fadeLayerIn{
	return TRUE;
}

- (void)setDeletterboxAssetArtwork:(BOOL)fp8{

}



- (id)popAnimation{
	id animation = [super popAnimation];
	return animation;
}


- (id)pushAnimation{
	id animation = [super pushAnimation];
	return animation;
}


-(BOOL)playClipNow{
	return m_playClipNow;
}

-(BOOL)skipClip{
	return m_skipClip;
}



- (BOOL)brEventAction:(BREvent*)event{
	BOOL ret = FALSE;

	//We are only interested in the key-down events.
	if([event value] == 0){
		return [super brEventAction:event];
	}

	if([[[NSUserDefaults standardUserDefaults] objectForKey:CTVCONF_CHANNELVIEW] isEqualToString:@"Yes"] ){

		switch([event remoteAction]){
			case kBRRemoteActionUp:
				m_playNextChannel = YES;		
				//Remove ourselves from screen
				m_timer = [NSTimer scheduledTimerWithTimeInterval:0.25 target:self selector:@selector(_timerCloseHandler:) userInfo:nil repeats:NO];
				[m_timer retain];
				ret = TRUE; //We handled the event
				break;
			case kBRRemoteActionDown:
				m_playPrevChannel = YES;		
				//Remove ourselves from screen
				m_timer = [NSTimer scheduledTimerWithTimeInterval:0.25 target:self selector:@selector(_timerCloseHandler:) userInfo:nil repeats:NO];
				[m_timer retain];
				ret = TRUE; //We handled the event
				break;
		}
	}else{
		//Clip view mode
		ret = FALSE;
	}
	
	if(ret == FALSE){
		ret = [super brEventAction:event];
	}
		
	return ret;
}

-(BOOL)playChannelNext{
	return m_playNextChannel;
}

-(BOOL)playChannelPrev{
	return m_playPrevChannel;
}


//CTVMediaDownloadUpdate
-(void)downloadPercent:(int)pc{
	
	//Total MB
	if(m_filesize <= 0){
		m_filesize = [m_downloader downloadFileLength];
		NSString* tmpstr = [NSString stringWithFormat:@"%dMB", (m_filesize/(1024*1024)) ]; 
		[m_progressBarContoller setMB:tmpstr];
	}
	
	[m_progressBarContoller setPercent:pc];
	[m_progressBarContoller redraw];
}


-(void)downloadTimeLeft:(int)timeLeft{
//NSLog(@"downloadTimeLeft...... : %d", timeLeft);

	NSString* tmpstr = [NSString stringWithFormat:@"%@", [CTVUtil getTimeRepresentationString:timeLeft fullDetail:TRUE fullNames:FALSE] ]; 
	[m_progressBarContoller setTimeLeft:tmpstr];
	[m_progressBarContoller redraw];
}



-(void)downloadFinish{
	m_downloader = nil;
	
	if([[[NSUserDefaults standardUserDefaults] objectForKey:CTVCONF_CHANNELVIEW] isEqualToString:@"Yes"] ){
		//Channel mode
		//We are not needed any more, remove ourselve from screen to start clip playback
		m_playClipNow = TRUE;
		[[self stack] removeController:self];
	}else{
		//CLip mode
		[m_progressBarContoller setTimeLeft:@""];
		[m_progressBarContoller setMB:@""];

		[m_abortButton setAction:@selector(playClipDownload)];
		[m_abortButton  setTitle:@"Play Clip"];
		[[self scene] renderScene];
	}
}


-(void)downloadError:(int)errorcode{
	switch(errorcode){
		case CTVDownloadError:
		case CTVDownloadErrorConnection:		
		case CTVDownloadErrorFileSize:
			//Notify a download error
			[m_abortButton setAction:@selector(finishClipDownload)];
			[m_abortButton  setTitle:@"Download Error"];
			[[self scene] renderScene];
			break;
		case CTVDownloadErrorAbort:
			//Release this screen
			[m_abortButton setAction:@selector(finishClipDownload)];
			[m_abortButton  setTitle:@"Download Aborted"];
			[[self scene] renderScene];
			break;
	}

	
	if([[[NSUserDefaults standardUserDefaults] objectForKey:CTVCONF_CHANNELVIEW] isEqualToString:@"Yes"] ){
		//Channel mode
		//We are not needed any more, remove ourselve from screen to continue playback
		m_skipClip = TRUE;
		[[self stack] removeController:self];
	}
				
	m_downloader = nil;
}


//Private
-(void)_timerCloseHandler:(NSTimer*)timer{
	[[self stack] removeController:self];	
}


@end
